# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
#     https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
#     https://docs.fastlane.tools/plugins/available-plugins
#

# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane

default_platform(:ios)

platform :ios do

  # 版本处理
  def setup_version_build(options)
    if "#{options[:build]}".empty?
      increment_build_number(
        xcodeproj: ENV['Xcodeproj']
      )
    else
      increment_build_number(
        xcodeproj: ENV['Xcodeproj'],
        build_number:options[:build]
      )
    end

    unless "#{options[:version]}".empty?
      increment_version_number(
        xcodeproj: ENV['Xcodeproj'],
        version_number:options[:version]
      )
    end
  end

  # 自定义build函数
  def custom_build_app (output_directory, export_method, options)
    current_time = Time.new.strftime("%Y-%m-%d-%H-%M-%s")
    output_name = "#{current_time}.ipa"

    provisioningProfile = ENV['App_Store_ProvisioningProfile']
    if "#{export_method}" == "ad-hoc"
      provisioningProfile = ENV['Ad_Hoc_ProvisioningProfile']
    end

    build_app(
      scheme: ENV['Scheme'],
      silent: true,
      clean: true,
      output_directory: "#{output_directory}",
      output_name: output_name,
      export_xcargs: "-allowProvisioningUpdates",
      export_options: {
        method: "#{export_method}",
        provisioningProfiles: { 
          ENV['App_Identifier'] => provisioningProfile
        }
      }
    )
  end

  # 任务执行前
  before_all do
    puts "任务执行开始了"
  end

  # 上传TestFlight
  desc "Push a new beta build to TestFlight"
  lane :beta do |options|
  	setup_version_build(options)
    custom_build_app ENV['TestFlight_Output_Path'],"app-store",options
    upload_to_testflight
  end

  # 上传AppStore
  desc "Push a new beta build to AppStore"
  lane :release do |options|
    setup_version_build(options)
    custom_build_app ENV['AppStore_Output_Path'],"app-store",options
    upload_to_app_store(
    	force: true # Set to true to skip verification of HTML preview
    )
  end

  # 上传蒲公英
  desc "Push a new release build to Pgy"
  lane :pgy do |options|
    setup_version_build(options)
    custom_build_app ENV['Pgy_Output_Path'],"ad-hoc",options
   	pgyer(api_key:ENV['Pgy_Api_Key'], user_key:ENV['Pgy_User_Key'])
  end

  # 上传Fir
  desc "Push a new release build to the Fir"
  lane :fir do |options|
    setup_version_build(options)
    custom_build_app ENV['Firim_Output_Path'],"ad-hoc",options
    firim(firim_api_token:ENV['Firim_Token'])
  end

  # 任务执行完毕
  after_all do |lane, options|
    puts"结束了"
  end

  # 任务执行异常
  error do |lane, exception, options|
     puts "任务执行异常"
  end

end
